<?php
// +----------------------------------------------------------------------
// | FileName: ip2regionService.php
// +----------------------------------------------------------------------
// | Date: 2022/12/19 12:55:24
// +----------------------------------------------------------------------
// | Author: 默毅 <moyi@mymoyi.cn>
// +----------------------------------------------------------------------
// | Notes: 
// +----------------------------------------------------------------------

namespace App\Service\Library;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;

class ip2regionService
{
    private $dbFile = NULL;
    private $cBuff = NULL;
    private $searcher = null;

    /**
     * construct method
     *
     * @param string ip2regionFile
     * @throws \Exception
     */
    public function __construct($ip2regionFile = null)
    {

        $this->dbFile = is_null($ip2regionFile) ? __DIR__ . '/res/ip2region.xdb' : $ip2regionFile;
        // 从 dbPath 加载整个 xdb 到内存。
        $this->cBuff = XdbSearcher::loadContentFromFile($this->dbFile);
        print_r(PHP_EOL);
        if ($this->cBuff === null) {
            print_r("IP查询库初始化失败");
            print_r(PHP_EOL);
        }else{
            print_r('初始化一次ip库的xdb类');
            print_r(PHP_EOL);
            $this->searcher = XdbSearcher::newWithBuffer($this->cBuff);
        }
    }

    /**
     * @return mixed|string
     */
    public function getDbFile(): mixed
    {
        return $this->dbFile;
    }

    public function search($ip): ?string
    {
        return $this->searcher->search($ip);
    }
}